const app = getApp();
const key = app.globalData.key;
const env = app.globalData.env;
const service = app.globalData.service;
const contextPath = app.globalData.contextPath;
const maxDistance = app.globalData.maxDistance;

Page({
    data: {
        event: {},
        userName: '',
        userPhone: '',
        userNote: ''
    },

    onLoad: function (options) {
        const itemString = decodeURIComponent(options.item || '{}');
        const item = JSON.parse(itemString);

        if (item) {
            this.setData({
                event: item
            });
        } else {
            wx.showToast({
                title: '未找到活动信息',
                icon: 'none',
                duration: 1500
            });
        }
    },


    onInputChange: function (e) {
        const field = e.currentTarget.dataset.field;
        this.setData({
            [field]: e.detail.value
        });
    },

    submitReservation: async function () {
        const {
            userName,
            userPhone,
            userNote,
            event
        } = this.data;
        if (!userName || !userPhone) {
            wx.showToast({
                title: '请填写完整信息',
                icon: 'none',
                duration: 1500
            });
            return;
        }
        // 将 userPhone 保存到 Storage
        wx.setStorageSync('userPhone', userPhone);

        // 构造请求 URL（根据您的 API 接口进行调整）
        const url = `${contextPath}/reservations?userName=${encodeURIComponent(userName)}&userPhone=${encodeURIComponent(userPhone)}&userNote=${encodeURIComponent(userNote)}&eventId=${encodeURIComponent(event.id)}`;

        try {
            const res = await wx.cloud.callContainer({
                config: {
                    env: env,
                },
                path: `${contextPath}/reservations`, // 修改为不带参数的路径
                method: 'POST',
                header: {
                    'X-WX-SERVICE': service,
                    'Content-Type': 'application/json', // 确保设置了正确的Content-Type
                },
                data: { // 将参数放在请求体中
                    userName: userName,
                    userPhone: userPhone,
                    userNote: userNote,
                    eventId: event.id,
                },
            })
            if (res.data) {
                wx.showToast({
                    title: '预约成功',
                    icon: 'success',
                    duration: 1500
                });
            } else {
                wx.showToast({
                    title: '预约失败',
                    icon: 'none',
                    duration: 1500
                });
            }
        } catch (error) {
            wx.showToast({
                title: '预约失败',
                icon: 'none',
                duration: 1500
            });
            console.error('API 调用失败：', err);
        }
    }
});